/**
 * @Time: 2018/11/22 14:07
 * @Author: wangmin
 * @File: block
 * @Software: GoLand
 */
package block

import (
	"open_manjing/oss/models"
	"github.com/astaxie/beego/orm"
	"errors"
	"regexp"
)

//对象存储区域模型
type Block struct {
	models.App
}

//添加存储块
func (m *Block) Add(name string, auth int8) (error, int) {
	if name == "" {
		return errors.New("块名称不能为空"), 0
	}
	matched, err := regexp.MatchString(`^\w+$`, name)
	if !matched {
		return errors.New("块名称格式错误只能是数字、字母、下划线"), 0
	}
	if m.Ormer.QueryTable("Block").Filter("Name", name).Exist() {
		return errors.New("块名称重复"), 0
	}
	if !StatusValueExists("Auth", auth) {
		return errors.New("块的权限级别设置有误"), 0
	}
	b := &models.Block{
		Name: name,
		Auth: auth,
	}
	id, err := m.Ormer.Insert(b)
	if err != nil {
		return err, 0
	}
	return nil, int(id)
}

//删除存储块
func (m *Block) Del(name string) error {
	b := &models.Block{
		Name: name,
	}
	err := m.Ormer.Read(b, "Name")
	switch err {
	case nil:
		if m.Ormer.QueryTable("Object").Filter("Bid", b.Id).Exist() {
			return errors.New("该存储块不为空无法删除")
		}
		_, err = m.Ormer.QueryTable("Block").Filter("Id", b.Id).Delete()
		return err
	case orm.ErrNoRows:
		return errors.New("存储块不存在")
	default:
		return err
	}
}

//重新设置权限
func (m *Block) ResetAuth(name string, auth int8) error {
	b := &models.Block{
		Name: name,
	}
	err := m.Ormer.Read(b, "Name")
	switch err {
	case nil:
		b.Auth = auth
		m.Ormer.Update(b, "Auth")
		return nil
	case orm.ErrNoRows:
		return errors.New("块不存在")
	default:
		return errors.New("服务器异常：" + err.Error())
	}
}

//根据id获取name值
func (m *Block) GetNameById(id int) string {
	b := &models.Block{}
	m.Ormer.QueryTable("Block").Filter("Id", id).One(b, "Name")
	return b.Name
}

//Instance
func Instance(o orm.Ormer) *Block {
	i := &Block{
	}
	i.Ormer = o
	return i
}
